package com.common.config;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.system.util.RedisUtils;
import com.system.entity.Teacher;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


/**
 * @author zfc
 * @date 2023-04-23 14:35:35
 */
@Component
public class MybastisColumnsHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        String[] getterNames = metaObject.getGetterNames();

        insertAndUpdate(getterNames,metaObject,"insert");
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String[] getterNames = metaObject.getGetterNames();

        insertAndUpdate(getterNames,metaObject,"update");
    }

    @Autowired
    private RedisUtils redisUtils;

    public void insertAndUpdate(String [] names, MetaObject metaObject, String type){
        String subject =(String) SecurityUtils.getSubject().getPrincipal();
        String result = (String) redisUtils.get(subject);
        try {
            Teacher teacher = JSON.parseObject(result, Teacher.class);
            for (String getter : names){
                if (getter.equals("createDate") && type.equals("insert")){
                    metaObject.setValue("createDate", LocalDateTime.now());
                }else if (getter.equals("creator") && type.equals("insert")){
                    metaObject.setValue("creator",teacher.getName());
                }else if (getter.equals("modifyDate") && type.equals("update")){
                    metaObject.setValue("modifyDate", LocalDateTime.now());
                }else if (getter.equals("creator") && type.equals("update")){
                    metaObject.setValue("modifier",teacher.getName());
                }
            }
        }catch (NullPointerException e){
            throw new NullPointerException("验证过期，请重新登录！");
        }
    }
}
